//
//  ShareViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/22.
//

import UIKit
import AudioToolbox
import Social
import FacebookShare

typealias ShareViewControllerBlock = ()->Void

class ShareViewController: BaseViewController {

    var callBack: ShareViewControllerBlock?
    var bkgAlphaBtn: UIButton!
    var bgView: UIView!
    var contentH: CGFloat = 266
    var titleStr: String = ""
    var shareBtn: UIButton!
    var whatsAppLab: UILabel!
    var faceBookBtn: UIButton!
    var faceBookLab: UILabel!
    var isfaceBook = false
    var copyLinkBtn: UIButton!
    var copyLinkLab: UILabel!
    
    var shareContent: String = ""
    var shareUrl = ""
    var phone: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.isHidden = true
        self.view.backgroundColor = .clear
        self.initSubiew()
        self.setUpHeaderView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimationAction()
        
    }
    
    func initSubiew() {
        //
        self.bkgAlphaBtn = UIButton.init(type: UIButtonType.custom)
        self.bkgAlphaBtn.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        self.bkgAlphaBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0)
        self.bkgAlphaBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
        self.view.addSubview(self.bkgAlphaBtn)
        
        self.bgView = UIView(frame: CGRect(x: 0, y: kScreenWidth, width: kScreenWidth, height: kScreenHeight))
        self.bgView.backgroundColor = .white
        self.bkgAlphaBtn.addSubview(self.bgView)
        bgView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
        
    }
    
    ///顶部 TitleLabel有半圆
    func setUpHeaderView(){
        
        let tempHeaderView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: contentH))
        //做圆角背景
        tempHeaderView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 56)
        tempHeaderView.backgroundColor = UIColor.white
        tempHeaderView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
        self.bgView.addSubview(tempHeaderView)
        
        let tempTitleLab = UILabel.init(frame: CGRect.init(x: kScreenWidth/2 - 160, y: 0, width: 320, height: 56))
        tempTitleLab.backgroundColor = UIColor.clear
        tempTitleLab.textAlignment = .center
        tempTitleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        tempTitleLab.textColor = Theme.titleLabColor
        tempTitleLab.numberOfLines = 0
        tempTitleLab.text = self.titleStr
        tempHeaderView.addSubview(tempTitleLab)
        
    
        
        shareBtn = UIButton(frame: CGRect(x: kScreenWidth/2 - 80, y: tempTitleLab.bottom + 30, width: 40, height: 40))
        shareBtn.setImage(UIImage(named: "icon_share_whtasApp"), for: .normal)
        shareBtn.addTarget(self, action: #selector(shareBtnAction), for: .touchUpInside)
        shareBtn.contentHorizontalAlignment = .right
        shareBtn.backgroundColor = .clear
        self.bgView.addSubview(shareBtn)
        
        whatsAppLab = UILabel(frame: CGRect(x: shareBtn.left - 55, y: shareBtn.bottom + 14, width: 150, height: 20))
        whatsAppLab.text = "WhatsApp"
        whatsAppLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        whatsAppLab.textColor = Theme.titleLabColor
        whatsAppLab.textAlignment = .center
        self.bgView.addSubview(whatsAppLab)
        
       
        copyLinkBtn = UIButton.init(frame: CGRect.init(x: shareBtn.right + 95, y: tempTitleLab.bottom + 30, width: 40, height: 40))
        
        copyLinkBtn.setImage(UIImage(named: "icon_copy_link"), for: .normal)
        copyLinkBtn.addTarget(self, action: #selector(copyLinkBtnAntion), for: .touchUpInside)
        copyLinkBtn.contentHorizontalAlignment = .right
        copyLinkBtn.backgroundColor = .clear
        self.bgView.addSubview(copyLinkBtn)
        
        copyLinkLab = UILabel(frame: CGRect(x: copyLinkBtn.left - 55, y: shareBtn.bottom + 14, width: 150, height: 20))
        copyLinkLab.text = MMLocalizedString("copy_link", comment: "复制链接")
        copyLinkLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        copyLinkLab.textColor = Theme.titleLabColor
        copyLinkLab.textAlignment = .center
        self.bgView.addSubview(copyLinkLab)
        
        let line = UIView(frame: CGRect(x: 0, y: copyLinkLab.frame.maxY + 34, width: kScreenWidth, height: 1))
        line.backgroundColor = UIColor(hex: 0xE1E3E6)
        self.bgView.addSubview(line)
        
        let cancelBtn = UIButton.init(frame: CGRect.init(x: 0, y: line.frame.maxY, width: kScreenWidth, height: 50))
        cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .normal)
        cancelBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        cancelBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCRegular, size: 14)
        cancelBtn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
        cancelBtn.backgroundColor = .white
        self.bgView.addSubview(cancelBtn)
        
        
        
//        if self.isfaceBook == true {
//
//            shareBtn.frame = CGRect(x: kScreenWidth/2 - 80, y: tempTitleLab.bottom + 50, width: 40, height: 40)
//            whatsAppLab.frame  = CGRect(x: shareBtn.left - 55, y: shareBtn.bottom + 14, width: 150, height: 20)
//
//            faceBookBtn = UIButton.init(frame: CGRect.init(x: shareBtn.right + 95, y: tempTitleLab.bottom + 50, width: 40, height: 40))
//            faceBookBtn.setImage(UIImage(named: "icon_share_Facebook"), for: .normal)
//            faceBookBtn.addTarget(self, action: #selector(facebookBtnAction), for: .touchUpInside)
//            faceBookBtn.contentHorizontalAlignment = .right
//            faceBookBtn.backgroundColor = .clear
//            self.bgView.addSubview(faceBookBtn)
//
//            faceBookLab = UILabel(frame: CGRect(x: faceBookBtn.left - 55, y: shareBtn.bottom + 14, width: 150, height: 20))
//            faceBookLab.text = "Facebook"
//            faceBookLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
//            faceBookLab.textColor = Theme.titleLabColor
//            faceBookLab.textAlignment = .center
//            self.bgView.addSubview(faceBookLab)
//        }
        
    }
    
    ///确定
    @objc func closeBtnAction(){
        self.hiddenActionView()
    }
    
    @objc func shareBtnAction() {
//        if self.isfaceBook == true {
//            faceBookLab.text = "Facebook"
//            faceBookLab.textColor = Theme.titleLabColor
//        }
     
        var tempStr = self.shareContent
        tempStr = tempStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
//        guard let url = URL.init(string: "whatsapp://send?phone=85266362553&text=\(tempStr)") else {
//            return
//        }
       
        var tempUrl = "whatsapp://send?text=\(tempStr)"
        if (self.phone != "") {
            tempUrl = "whatsapp://send?phone=\(self.phone)&text=\(tempStr)"
        }
        guard let url = URL.init(string: tempUrl) else {
            return
        }
      
        if UIApplication.shared.canOpenURL(url) {
            let opts = UIViewAnimationOptions.curveEaseInOut
            UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
                self.bkgAlphaBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
                self.bgView.frame.origin.y = kScreenHeight
            }, completion: { _ in
                self.dismiss(animated: false) {
                
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            })
        }else{
            AudioServicesPlaySystemSoundWithCompletion(1519) {
                //system振动效果 一响
            }
            self.shareBtn.layer.add(self.shakeAnimate(repeatCount: 8, duration: 0.2, values: [-Double.pi/12, Double.pi/12,-Double.pi/12]), forKey: nil)
            self.view.makeToast(message: MMLocalizedString("not_install_whatsapp_tip", comment: "请下载WhatsApp!"))
           
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {[weak self] in
                self?.hiddenActionView()
            }
        }
    }
    
    ///页面展示动画
    @objc func startAnimationAction(){
        self.view.handleLoading()
        self.bgView.frame.origin.y = kScreenHeight
        self.bkgAlphaBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0 )
        let orginY = kScreenHeight - self.contentH
        UIView.animate(withDuration: 0.2, animations: {
            self.bkgAlphaBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.6)
            self.bgView.frame.origin.y = orginY
        }) { (flag) in
            //
        }
    }
    
    @objc func copyLinkBtnAntion(){
        let past = UIPasteboard.general//系统自带的复制
        past.string = self.shareUrl
        self.view.makeToastBottom(message: MMLocalizedString("copy_link_successed", comment: "复制链接成功"))
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {[weak self] in
            self?.hiddenActionView()
        }
    }
    
    
    @objc func facebookBtnAction() {
        if self.isfaceBook == true {
            whatsAppLab.text = "WhatsApp"
            whatsAppLab.textColor = Theme.titleLabColor
        }
         var tempStr = self.shareContent
        tempStr = tempStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        guard let url = URL(string: tempStr) else {
          return
        }
        self.detectInstalled(URLString: "fbapi://",shareUrl: url)
    }
    
    func detectInstalled(URLString: String?,shareUrl: URL) {
        if let URLString = URLString, let exsistURL = URL(string: URLString), UIApplication.shared.canOpenURL(exsistURL) {
            let content = ShareLinkContent()
            content.contentURL = shareUrl
            let dialog = ShareDialog(
                fromViewController: self,
                content: content,
                delegate: self
            )
            dialog.show()
        } else {
       
            AudioServicesPlaySystemSoundWithCompletion(1519) {
                //system振动效果 一响
            }
            self.faceBookBtn.layer.add(self.shakeAnimate(repeatCount: 8, duration: 0.2, values: [-Double.pi/12, Double.pi/12,-Double.pi/12]), forKey: nil)
            self.view.makeToast(message:MMLocalizedString("not_install_facebook_tip", comment: "请下载Facebook!"))
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {[weak self] in
                self?.hiddenActionView()
            }
        }
    }

    
    
    /// 隐藏,没有点添加到购物车按钮
    @objc func hiddenActionView(){
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
            self.bkgAlphaBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
            self.bgView.frame.origin.y = kScreenHeight
        }, completion: { _ in
            self.callBack?()
            self.dismiss(animated: false) {
            }
        })
    }
    
    @objc func cancelBtnAction(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.hiddenActionView()
        }
    }
    
    func shakeAnimate(repeatCount:Float,duration:CFTimeInterval,values:[Any]) -> CAKeyframeAnimation {
        let keyAnimation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
        keyAnimation.delegate = self
        //开始时间
        keyAnimation.beginTime = CACurrentMediaTime()
        //持续时间 0.2
        keyAnimation.duration = duration
        
        keyAnimation.values = values
        //重复次数 3
        keyAnimation.repeatCount = repeatCount
        //完成后是否移除
        keyAnimation.isRemovedOnCompletion = true
        return keyAnimation
    }
}

extension ShareViewController: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
            self.shareBtn.layer.removeAnimation(forKey: "transform.rotation")
        }
    }
}


extension ShareViewController:  SharingDelegate{
    
       func sharer(_ sharer: Sharing, didCompleteWithResults results: [String : Any]) {
          print(results)
       }
       
       func sharer(_ sharer: Sharing, didFailWithError error: Error) {
           print(error)
       }
       
       func sharerDidCancel(_ sharer: Sharing) {
           print(sharer)
       }
       
}

